var express = require('express');
var router = express.Router();
var mongoose = require("../../mongoose")

//创建产品Schema
var schema = new mongoose.Schema({
    id: { type: String, require: true },//id
    name: { type: String, require: true },//分类名称
});
// 定义MongoDB数据模型 (表>=集合)
var imageTab = mongoose.model("imageTabs", schema);
var random = require("../../utils/randomUser")
// 添加分类
router.post('/create', async function (req, res, next) {
    let body = {
        name: req.body.name
    }
    const dataobj = await imageTab.find()
    const imageTablist = await imageTab.find({ name: req.body.name })
    if (imageTablist.length == '') {
        body.id = random('id-' + dataobj.length + 1 + '-', 5)
        imageTab.create(body).then((data) => {
            res.send({
                code: 200,
                success: true,
                msg: "添加成功",
                data
            })
        }).catch((err) => {
            res.send({
                code: 500,
                success: false,
                msg: "添加失败"
            })
        });
    } else {
        res.send({
            code: 300,
            success: false,
            msg: "分类名已存在"
        })
    }


})

//查询tab列表信息
router.get('/list', async function (req, res, next) {
    await imageTab.find({}).then((data) => {
        res.send({
            code: 200,
            success: true,
            msg: "列表查询成功",
            data,
        })
    }).catch((err) => {
        res.send({
            code: 500,
            success: false,
            msg: "列表查询失败",
            data: err
        })
    });

})
//删除分类
router.post('/deleteClass', async function (req, res, next) {
    await imageTab.deleteOne({
        id: req.body.id
    }).then(data => {
        res.send({
            code: 200,
            msg: "已删除",
            success: true,
            data,
        })
    }).catch((err) => {
        res.send({
            code: 500,
            success: false,
            msg: "删除失败",
            data: err
        })
    });
})
module.exports = router;